let { globalData, globalData: { BaseUrl, commonUrl, active }, cloud, showToast, track } = getApp();
import * as PIXI from "@tbminiapp/pixi-miniprogram-engine";
import { throttle, deepClone } from '../../utils/tools';
import { gsap } from 'gsap';

let startX = 0
let startTime = 0

Page({
  data: {
    BaseUrl: BaseUrl,
    isPlay: false,
    isPhoneX: false,
    opacityVal: 0,
    areaRectPos: [],
    videoRectPos: [],

    textMoveVal: 0,
    showBottleInfo: false,

    showVideodPoster0: true,
    showVideodPoster1: true,
    showVideodPoster2: true,
    showVideodPoster3: true,

    showOwnerBtn: false,
    showBtnTips: false,
    showSlideTips: true,

    showScaleAni: false,
    showMainTile: false,
    showMainBtn: false,
    showApng: false,

    playingVideo: null,  // 当前正在播放的视频索引
    imgStyle: "",
    isShowAni: false,
    canClick: false,

    moveTransArr: [
      { text: 'On a tous', y: 0 },
      { text: 'besoin', y: 0 },
      { text: 'd’une goutte', y: 0 },
    ]

  },
  onLoad(query) {
    track("", "flowSource")
    track("香奈儿MB页面", "")
    // 隐藏返回到首页的按钮
    my.hideBackHome({});
    my.setNavigationBar({ title: "全新香奈儿五号之水" });
    my.getSystemInfo({
      success: (res) => {
        if (res.screenWidth / res.screenHeight <= 0.51) {
          this.setData({ isPhoneX: true });
          globalData.isPhoneX = true
        }
      }
    })

    // 获取scrollHeight
    my.createSelectorQuery()
      .select('.main_page').boundingClientRect()
      .exec((res) => {
        if (res && res[0]) {
          this.setData({
            scrollHeight: res[0].height, //滑动区域的高度
          });
        }
      })

    //获取视频的Rect值
    my.createSelectorQuery()
      .select('.chanel_video0').boundingClientRect()//0
      .select('.first_video_container').boundingClientRect()//1
      .select('.second_video_container').boundingClientRect()//2
      // .select('.third_video_container').boundingClientRect()//3
      .select('.four_video_container').boundingClientRect()//4
      .exec((res) => {
        let videoRectPos = [];
        for (var i = 0, len = res.length; i < len; i++)
          videoRectPos.push(res[i]);
        console.log("videoRectPos", videoRectPos);
        this.setData({ videoRectPos })
      });


    // 获取其他内容的Rect值
    my.createSelectorQuery()
      .select('.main_title_container').boundingClientRect()//0
      .select('.mid_small_text_container').boundingClientRect()//1
      .select('.model_img_container').boundingClientRect()//2
      .exec((res) => {
        let areaRectPos = [];
        for (var i = 0, len = res.length; i < len; i++)
          areaRectPos.push(res[i]);
        console.log("areaRectPos", areaRectPos);
        this.setData({ areaRectPos })
      });
    this.playVideo(0)

  },


  handleScroll(event) {

    let { areaRectPos, videoRectPos, scrollHeight, textMoveVal } = this.data;
    // 获取当前滚动的位置和上次滚动的位置
    let { scrollTop } = event.detail;
    const range = (this.data.scrollHeight - 400);
    let opacityVal = 0;
    // 对透明度进行边界处理，确保在合理范围内
    if (scrollTop > range) {
      opacityVal = (scrollTop - range) / range;
    }
    opacityVal = Math.max(0, Math.min(1, opacityVal));
    this.setData({ opacityVal })

    //首屏按钮 和 提示的显示和隐藏
    if (scrollTop > areaRectPos[0].bottom - 100) {
      this.setData({ showSlideTips: false, showBtnTips: false, showBottleAni: true });
    } else {
      this.setData({ showSlideTips: true, showBtnTips: true });
    }

    // 文案上移动画
    let maxMoveVal = 180;
    let minMoveVal = 0;
    let moveVal = Math.min(maxMoveVal, Math.max(minMoveVal, (scrollTop - (areaRectPos[1].top - scrollHeight)) / 500 * 180));
    // console.log("====moveVal=====",moveVal);
    this.setData({ textMoveVal: moveVal })

    // 模特图片
    if (scrollTop > (areaRectPos[2].top - scrollHeight / 2) + 100) {
      console.log(" 模特图片")
      this.setData({ showOwnerBtn: true })
    } else {
      this.setData({ showOwnerBtn: false })
    }

    if (scrollTop > scrollHeight && !this.data.showScaleAni) {
      this.setData({ showScaleAni: true }, () => {
        setTimeout(() => {
          this.setData({ showMainTile: true });
        }, 400);
        setTimeout(() => {
          this.setData({ showMainBtn: true });
        }, 700);
      })
    }


    // 根据滑动的距离 改变瓶子的角度
    let scrollRangeStart = scrollHeight;
    let scrollRangeEnd = videoRectPos[1].top - scrollHeight + 1000;
    if (scrollTop >= scrollRangeStart && scrollTop <= scrollRangeEnd && this.data.showScaleAni) {
      let maxRotate = 17.76;
      let minRotate = -17.76;
      let rotate = 0
      let maxRotateX = 1.97;
      let minRotateX = -1.97;
      let rotateX = 0
      let maxRotateY = 12.48;
      let minRotateY = 12.48;
      let rotateY = 0
      let maxSkew = 0.432;
      let minSkew = -0.432;
      let skew = 0
      // 检查滑动是否在指定区域内
      if (scrollTop >= scrollRangeStart && scrollTop <= scrollRangeEnd) {
        const range = scrollRangeEnd - scrollRangeStart;
        const relativeScroll = (scrollTop - scrollRangeStart) % range; // 相对于滑动区域起始位置的相对滚动距离
        const thirdRange = range / 3;
        // console.log("range,relativeScroll,thirdRange", range, relativeScroll, thirdRange);
        if (relativeScroll <= thirdRange) {
          // 在滑动区域的第一阶段，递增
          rotate = (relativeScroll / thirdRange) * maxRotate;
          rotateX = (relativeScroll / thirdRange) * maxRotateX;
          rotateY = (relativeScroll / thirdRange) * maxRotateY;
          skew = (relativeScroll / thirdRange) * maxSkew;
        } else if (relativeScroll <= 2 * thirdRange) {
          // 在滑动区域的第二阶段，递减
          rotate = maxRotate - ((relativeScroll - thirdRange) / thirdRange) * (maxRotate - minRotate);
          rotateX = maxRotateX - ((relativeScroll - thirdRange) / thirdRange) * (maxRotateX - minRotateX);
          rotateY = maxRotateY - ((relativeScroll - thirdRange) / thirdRange) * (maxRotateY - minRotateY);
          skew = maxSkew - ((relativeScroll - thirdRange) / thirdRange) * (maxSkew - minSkew);
        } else {
          //在滑动区域的第三阶段，递增
          rotate = minRotate + ((relativeScroll - 2 * thirdRange) / thirdRange) * (maxRotate - minRotate);
          rotateX = minRotateX + ((relativeScroll - 2 * thirdRange) / thirdRange) * (maxRotateX - minRotateX);
          rotateY = minRotateY + ((relativeScroll - 2 * thirdRange) / thirdRange) * (maxRotateY - minRotateY);
          skew = minSkew + ((relativeScroll - 2 * thirdRange) / thirdRange) * (maxSkew - minSkew);
        }
        this.setData({ imgStyle: `transform:rotate(${rotate}deg) rotateY(${rotateY}deg) rotateX(${rotateX}deg) skew(${skew}deg, 0deg);  transform-origin: 50% 50%;" ` })
      }
    }
    if (scrollTop >= videoRectPos[2].bottom - 400) {
      this.setData({ imgStyle: `transform:rotate(0deg) rotateY(0deg) rotateX(0deg) skew(0deg, 0deg);  transform-origin: 50% 50%;` })
    }

    if (scrollTop >= videoRectPos[2].bottom - 200) {
      this.setData({ showBottleInfo: true })
    } else {
      this.setData({ showBottleInfo: false })
    }


    // 播放视频
    videoRectPos.forEach((item, index) => {
      if (item && item.top - scrollHeight < scrollTop && item.bottom > scrollTop) {
        if (this.data.playingVideo !== index) {
          this.playVideo(index)
        }
      } else {
        if (this.data.playingVideo === index) {
          this.pauseVideo(index)
        }
      }
    })

    if (scrollTop > videoRectPos[0].bottom - 30) {
      console.log("1234589")
      this.setData({ canClick: true })
    } else {
      this.setData({ canClick: false })
    }

  },


  playVideo(index) {
    const videoContext = my.createVideoContext(`chanel_video${index}`)
    videoContext.play()
    this.setData({ playingVideo: index })
  },

  pauseVideo(index) {
    const videoContext = my.createVideoContext(`chanel_video${index}`)
    videoContext.pause()
    this.setData({ playingVideo: null }, () => {
      setTimeout(() => {
        this.setData({ [`showVideodPoster${index}`]: true })
      }, 1000)
    })
  },


  onPlay(e) {
    let { index } = e.target.dataset
    setTimeout(() => {
      this.setData({ [`showVideodPoster${index}`]: false })
    }, 500)
    setTimeout(() => {
      this.setData({ isShowAni: true })
    }, 1500)

  },

  goAdd1: throttle(function () {

    if (this.data.showBottleInfo) {

      my.tb.showSku({
        itemId: '794637949358',
        success: (success) => {
          console.log("successsuccesssuccess", success)
        }
      })
    }
    track("旋转瓶子-即刻拥有")
  }, 800),

  goAdd2: throttle(function () {

    my.tb.showSku({
      itemId: '794637949358',
      success: (success) => {
        console.log("successsuccesssuccess", success)
      },
    })
    track("模特页-即刻拥有")
  }, 800),


  goAdd3: throttle(function () {

    if (this.data.canClick) {
      my.tb.showSku({
        itemId: '794637949358',
        success: (success) => {
          console.log("successsuccesssuccess", success)
        },
      })
    }
    track("首页-即刻拥有")
  }, 800),



  goDetail: throttle(function () {
      
    //    return
    // console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
    if (this.data.canClick) {
      my.tb.showSku({
        itemId: '794637949358',
        success: (success) => {
          console.log("successsuccesssuccess", success)
        },
        fail: (fail) => {
          console.log("failfailfailfailfailfail", fail)
        },
        complete: (complete) => {

          if (complete.errorMessage == '用户取消') {
            my.authorize({
              scopes: 'scope.camera',
              success: (res) => {
                 my.navigateTo({ url: "/pages/test/test" })
              },
            });

          }
        },
      })
    }
  }, 1000),


  // goAdd: throttle(function (e) {
  // 	console.log("e",e);
  // 	let {id} = e[0].currentTarget.dataset;
  // 	console.log("id",id);
  //     let str=id==1?'旋转瓶子-即刻拥有':id==2?"模特页-即刻拥有":'首页-即刻拥有'
  // 	if (this.data.showBottleInfo || (this.data.showBtnTips && this.data.showScaleAni) || this.data.showOwnerBtn) {
  // 		my.tb.showSku({
  // 			itemId: '794637949358',
  // 			success: (result) => { }
  // 		})
  // 	}
  // 	track(str)
  // }, 1000),









  onShareAppMessage() {
    return {
      title: "全新香奈儿之水",
      desc: "限定珍藏版",
      imageUrl: "https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2024Chanel_n5_drop/share.png",
      path: 'pages/main/main',
      success() { }
    }
  }
});